<template>
  <view class="dividend-page">
    <!-- 导航栏 -->
    <o-navbarx :back="true" color="#000000" background="#ffffff">
      <template #left_conent>
        <view class="nav-title">分红明细</view>
      </template>
    </o-navbarx>

    <!-- 月份选择器 -->
    <view class="month-selector">
      <view class="selector-item" @click="showMonthPicker = true">
        <text class="selector-text">{{ selectedMonth }}</text>
        <image src="/static/img/icon_jiantou_18.png" class="selector-arrow"></image>
      </view>
    </view>

    <!-- 分红统计卡片 -->
    <view class="stats-cards">
      <view class="stats-card" v-for="(stat, index) in dividendStats" :key="index">
        <view class="card-title">{{ stat.title }}</view>
        <view class="card-value">{{ stat.value }}</view>
        <view class="card-desc">{{ stat.desc }}</view>
      </view>
    </view>

    <!-- AB区业绩进度 -->
    <view class="ab-progress-section" v-if="abProgressData">
      <view class="section-title">我的AB区业绩进度</view>
      
      <!-- AB区业绩统计 -->
      <view class="ab-stats">
        <view class="ab-stat-item">
          <view class="stat-label">A区订单</view>
          <view class="stat-value">{{ abProgressData.ab_performance.a_area_orders }}单</view>
        </view>
        <view class="ab-stat-item">
          <view class="stat-label">B区订单</view>
          <view class="stat-value">{{ abProgressData.ab_performance.b_area_orders }}单</view>
        </view>
        <view class="ab-stat-item">
          <view class="stat-label">总订单</view>
          <view class="stat-value">{{ abProgressData.ab_performance.total_orders }}单</view>
        </view>
        <view class="ab-stat-item">
          <view class="stat-label">单区最小</view>
          <view class="stat-value">{{ abProgressData.ab_performance.min_area_orders }}单</view>
        </view>
      </view>

      <!-- 分红等级进度 -->
      <view class="level-progress-list">
        <view class="progress-item" v-for="progress in abProgressData.level_progress" :key="progress.level">
          <view class="progress-header">
            <view class="progress-title">{{ progress.name }}</view>
            <view class="progress-status" :class="{ 'qualified': progress.qualified }">
              {{ progress.qualified ? '已达标' : '未达标' }}
            </view>
          </view>
          
          <!-- 柱状图容器 -->
          <view class="chart-container">
            <!-- 总订单柱状图 -->
            <view class="chart-item">
              <view class="chart-label">
                <text class="chart-title">总订单</text>
                <text class="chart-value">{{ progress.current_total_orders }}/{{ progress.min_orders }}</text>
              </view>
              <view class="chart-bar-container">
                <view class="chart-bar">
                  <view 
                    class="chart-fill total-fill" 
                    :style="{ height: progress.total_orders_progress + '%' }"
                    :class="{ 'completed': progress.total_orders_progress >= 100 }"
                  ></view>
                </view>
                <view class="chart-percent">{{ Math.round(progress.total_orders_progress) }}%</view>
              </view>
            </view>
            
            <!-- A区柱状图 -->
            <view class="chart-item">
              <view class="chart-label">
                <text class="chart-title">A区</text>
                <text class="chart-value">{{ progress.a_area_orders }}/{{ progress.min_single_area }}</text>
              </view>
              <view class="chart-bar-container">
                <view class="chart-bar">
                  <view 
                    class="chart-fill a-area-fill" 
                    :style="{ height: progress.a_area_progress + '%' }"
                    :class="{ 'completed': progress.a_area_progress >= 100 }"
                  ></view>
                </view>
                <view class="chart-percent">{{ Math.round(progress.a_area_progress) }}%</view>
              </view>
            </view>
            
            <!-- B区柱状图 -->
            <view class="chart-item">
              <view class="chart-label">
                <text class="chart-title">B区</text>
                <text class="chart-value">{{ progress.b_area_orders }}/{{ progress.min_single_area }}</text>
              </view>
              <view class="chart-bar-container">
                <view class="chart-bar">
                  <view 
                    class="chart-fill b-area-fill" 
                    :style="{ height: progress.b_area_progress + '%' }"
                    :class="{ 'completed': progress.b_area_progress >= 100 }"
                  ></view>
                </view>
                <view class="chart-percent">{{ Math.round(progress.b_area_progress) }}%</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 分红等级列表 -->
    <view class="dividend-levels">
      <view class="level-item" v-for="level in dividendLevels" :key="level.level">
        <view class="level-header" @click="toggleLevel(level.level)">
          <view class="level-info">
            <view class="level-name">{{ level.name }}</view>
            <view class="level-desc">参与人数: {{ level.participantCount }}人</view>
          </view>
          <view class="level-amount">¥{{ level.totalAmount }}</view>
          <image 
            :src="level.expanded ? '/static/img/icon_jiantou_up.png' : '/static/img/icon_jiantou_down.png'" 
            class="level-arrow"
          ></image>
        </view>
        
        <!-- 参与者列表 -->
        <view class="participants-list" v-if="level.expanded">
          <view class="participant-item" v-for="participant in level.participants" :key="participant.user_id">
            <view class="participant-info">
              <image :src="participant.avatar_text" class="participant-avatar"></image>
              <view class="participant-details">
                <view class="participant-name">{{ participant.nickname }}</view>
                <view class="participant-level">等级: {{ participant.user_level }}</view>
              </view>
            </view>
            <view class="participant-amount">¥{{ participant.amount }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 月份选择器弹窗 -->
    <tm-time-picker
      v-model:show="showMonthPicker"
      v-model="selectedMonthValue"
      v-model:model-str="selectedMonth"
      :showDetail="{
        year: true,
        month: true,
        day: false,
        hour: false,
        minute: false,
        second: false
      }"
      format="YYYY-MM"
      :start="startDate"
      :end="endDate"
      title="选择月份"
      @confirm="onMonthConfirm"
    ></tm-time-picker>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { getDividendDetails, getABAreaProgress } from '@/utils/api'

// 类型定义
interface DividendStat {
  title: string
  value: string
  desc: string
}

interface Participant {
  user_id: number
  nickname: string
  avatar_text: string
  user_level: number
  amount: number
}

interface DividendLevel {
  level: number
  name: string
  participantCount: number
  totalAmount: number
  expanded: boolean
  participants: Participant[]
}

interface ApiResponse {
  code: number
  data: {
    totalAmount: number
    totalParticipants: number
    activeLevels: number
    levels: DividendLevel[]
  }
  msg?: string
}

interface ABProgressData {
  user_id: number
  month: string
  ab_performance: {
    total_orders: number
    min_area_orders: number
    area_orders: number[]
    a_area_orders: number
    b_area_orders: number
  }
  level_progress: Array<{
    level: number
    name: string
    min_orders: number
    min_single_area: number
    current_total_orders: number
    current_min_area_orders: number
    total_orders_progress: number
    a_area_progress: number
    b_area_progress: number
    qualified: boolean
    a_area_orders: number
    b_area_orders: number
  }>
}

// 响应式数据
const currentDate = new Date()
const currentYear = currentDate.getFullYear()
const currentMonth = currentDate.getMonth() + 1
const selectedMonth = ref(`${currentYear}-${currentMonth.toString().padStart(2, '0')}`)
const selectedMonthValue = ref(new Date()) // 使用 Date 对象
const showMonthPicker = ref(false)
const dividendStats = ref<DividendStat[]>([])
const dividendLevels = ref<DividendLevel[]>([])
const abProgressData = ref<ABProgressData | null>(null)

// 日期范围设置
const startDate = ref('2020/01/01 00:00:00') // 从2020年开始
const endDate = computed(() => {
  // 结束日期为当前月份的最后一天
  const year = currentDate.getFullYear()
  const month = currentDate.getMonth() + 1
  const lastDay = new Date(year, month, 0).getDate() // 获取当前月份的最后一天
  return `${year}/${month.toString().padStart(2, '0')}/${lastDay.toString().padStart(2, '0')} 23:59:59`
})

// 切换等级展开/收起
const toggleLevel = (level: number) => {
  const levelItem = dividendLevels.value.find(item => item.level === level)
  if (levelItem) {
    levelItem.expanded = !levelItem.expanded
  }
}

// 月份确认
const onMonthConfirm = (value: string) => {
  // value 是格式化的字符串，如 "2024/01/01 00:00:00"
  // 我们需要提取年月部分
  const dateStr = value.split(' ')[0] // 获取日期部分 "2024/01/01"
  const [year, month] = dateStr.split('/')
  selectedMonth.value = `${year}-${month.padStart(2, '0')}`
  loadDividendData()
  loadABProgressData()
}


// 加载分红数据
const loadDividendData = async () => {
  try {
    uni.showLoading({ title: '加载中...' })
    
    const response = await getDividendDetails({
      month: selectedMonth.value
    }) as ApiResponse
    
    if (response.code === 1) {
      const data = response.data
      
      // 设置统计数据
      dividendStats.value = [
        {
          title: '总分红金额',
          value: `¥${data.totalAmount}`,
          desc: '本月所有等级分红总额'
        },
        {
          title: '参与人数',
          value: `${data.totalParticipants}人`,
          desc: '获得分红的用户总数'
        }
      ]
      
      // 设置等级数据
      dividendLevels.value = data.levels.map((level: DividendLevel) => ({
        ...level,
        expanded: false
      }))
    } else {
      uni.showToast({
        title: response.msg || '加载失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('加载分红数据失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 加载AB区进度数据
const loadABProgressData = async () => {
  try {
    const response = await getABAreaProgress({
      month: selectedMonth.value
    }) as { code: number; data: ABProgressData; msg?: string }
    
    if (response.code === 1) {
      abProgressData.value = response.data
    } else {
      // 如果不是店长或没有权限，隐藏AB区进度
      abProgressData.value = null
      if (response.msg && !response.msg.includes('只有店长才能查看')) {
        console.warn('获取AB区进度失败:', response.msg)
      }
    }
  } catch (error) {
    console.error('加载AB区进度数据失败:', error)
    abProgressData.value = null
  }
}

// 页面加载
onMounted(() => {
  loadDividendData()
  loadABProgressData()
})
</script>

<style scoped lang="scss">
.dividend-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #000000;
}

.month-selector {
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  margin-bottom: 20rpx;
  
  .selector-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    background-color: #f8f8f8;
    border-radius: 12rpx;
    
    .selector-text {
      font-size: 32rpx;
      color: #333333;
    }
    
    .selector-arrow {
      width: 24rpx;
      height: 24rpx;
    }
  }
}

.stats-cards {
  display: flex;
  padding: 0 30rpx 20rpx;
  gap: 20rpx;
  
  .stats-card {
    flex: 1;
    background-color: #ffffff;
    border-radius: 16rpx;
    padding: 30rpx 20rpx;
    text-align: center;
    
    .card-title {
      font-size: 24rpx;
      color: #666666;
      margin-bottom: 10rpx;
    }
    
    .card-value {
      font-size: 36rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 8rpx;
    }
    
    .card-desc {
      font-size: 22rpx;
      color: #999999;
    }
  }
}

.dividend-levels {
  padding: 0 30rpx;
  
  .level-item {
    background-color: #ffffff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
    
    .level-header {
      display: flex;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
      
      .level-info {
        flex: 1;
        
        .level-name {
          font-size: 32rpx;
          font-weight: bold;
          color: #333333;
          margin-bottom: 8rpx;
        }
        
        .level-desc {
          font-size: 24rpx;
          color: #666666;
        }
      }
      
      .level-amount {
        font-size: 36rpx;
        font-weight: bold;
        color: #ff6b35;
        margin-right: 20rpx;
      }
      
      .level-arrow {
        width: 24rpx;
        height: 24rpx;
      }
    }
    
    .participants-list {
      .participant-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20rpx 30rpx;
        border-bottom: 1rpx solid #f8f8f8;
        
        &:last-child {
          border-bottom: none;
        }
        
        .participant-info {
          display: flex;
          align-items: center;
          flex: 1;
          
          .participant-avatar {
            width: 60rpx;
            height: 60rpx;
            border-radius: 50%;
            margin-right: 20rpx;
          }
          
          .participant-details {
            .participant-name {
              font-size: 28rpx;
              color: #333333;
              margin-bottom: 4rpx;
            }
            
            .participant-level {
              font-size: 22rpx;
              color: #666666;
            }
          }
        }
        
        .participant-amount {
          font-size: 32rpx;
          font-weight: bold;
          color: #ff6b35;
        }
      }
    }
  }
}

// AB区业绩进度样式
.ab-progress-section {
  margin: 20rpx 30rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 30rpx;
    text-align: center;
  }
  
  .ab-stats {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-bottom: 30rpx;
    
    .ab-stat-item {
      flex: 1;
      min-width: 140rpx;
      text-align: center;
      padding: 20rpx 10rpx;
      background-color: #f8f9fa;
      border-radius: 12rpx;
      
      .stat-label {
        font-size: 24rpx;
        color: #666666;
        margin-bottom: 8rpx;
      }
      
      .stat-value {
        font-size: 28rpx;
        font-weight: bold;
        color: #333333;
      }
    }
  }
  
  .level-progress-list {
    .progress-item {
      margin-bottom: 30rpx;
      padding: 20rpx;
      background-color: #f8f9fa;
      border-radius: 12rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .progress-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        
        .progress-title {
          font-size: 28rpx;
          font-weight: bold;
          color: #333333;
        }
        
        .progress-status {
          padding: 6rpx 16rpx;
          border-radius: 20rpx;
          font-size: 22rpx;
          background-color: #ff6b6b;
          color: #ffffff;
          
          &.qualified {
            background-color: #51cf66;
          }
        }
      }
      
       .chart-container {
         display: flex;
         justify-content: space-between;
         align-items: flex-end;
         gap: 40rpx;
         padding: 40rpx 30rpx;
         min-height: 280rpx;
         background-color: #fafafa;
         border-radius: 20rpx;
         margin: 20rpx 0;
        
        .chart-item {
          flex: 1;
          display: flex;
          flex-direction: column;
          align-items: center;
          
           .chart-label {
             display: flex;
             flex-direction: column;
             align-items: center;
             margin-bottom: 25rpx;
             
             .chart-title {
               font-size: 32rpx;
               color: #333333;
               font-weight: bold;
               margin-bottom: 8rpx;
             }
             
             .chart-value {
               font-size: 26rpx;
               color: #666666;
             }
           }
          
          .chart-bar-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
            
             .chart-bar {
               width: 80rpx;
               height: 200rpx;
               background-color: #e8e8e8;
               border-radius: 40rpx 40rpx 16rpx 16rpx;
               overflow: hidden;
               position: relative;
               display: flex;
               align-items: flex-end;
               box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
              
              .chart-fill {
                width: 100%;
                border-radius: 40rpx 40rpx 16rpx 16rpx;
                transition: height 0.8s ease;
                position: absolute;
                bottom: 0;
                box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
                
                &.total-fill {
                  background: linear-gradient(180deg, #4facfe 0%, #00f2fe 100%);
                  
                  &.completed {
                    background: linear-gradient(180deg, #51cf66 0%, #69db7c 100%);
                  }
                }
                
                &.a-area-fill {
                  background: linear-gradient(180deg, #ff6b6b 0%, #ff8e8e 100%);
                  
                  &.completed {
                    background: linear-gradient(180deg, #51cf66 0%, #69db7c 100%);
                  }
                }
                
                &.b-area-fill {
                  background: linear-gradient(180deg, #4ecdc4 0%, #44a08d 100%);
                  
                  &.completed {
                    background: linear-gradient(180deg, #51cf66 0%, #69db7c 100%);
                  }
                }
              }
            }
            
             .chart-percent {
               font-size: 28rpx;
               color: #333333;
               margin-top: 16rpx;
               font-weight: bold;
             }
          }
        }
      }
    }
  }
}
</style>
